class Observer {
  constructor(data) {
    this.walk(data)
  }

  // 遍历data，添加get/set拦截
  walk(data) {
    if (!data || typeof data !== "object") return
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
      // 如果data[key]也是个对象，则需要接着遍历
      this.walk(data[key])
    })
  }

  defineReactive(data, key, oldValue) {
    let _this = this
    let dep = new Dep()
    
    Object.defineProperty(data, key, {
      enumerable: true,
      configurable: true,
      get() {
        Dep.target && dep.addSub(Dep.target)
        return oldValue
      },
      set(newValue) {
        if (newValue === oldValue) return
        oldValue = newValue
        dep.notify()
        // 如果重新设置的值为object，也应该遍历，设置拦截
        _this.walk(newValue)
      },
    })
    // console.log(dep);
  }
}